package com.viphuli.http.handler;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.offroader.pay.weichat.WXPayOrder;
import com.offroader.pay.weichat.WeicahtPayHelper;
import com.offroader.utils.ViewUtils;
import com.viphuli.common.MyApp;
import com.viphuli.fragment.PurchaseOrderPayFragment;
import com.viphuli.http.bean.page.PurchaseOrderPayPage;
import com.viphuli.http.bean.part.PurchasePayInfo;

public class PurchaseOrderPayWeichatResponseHandler extends MyBaseHttpResponseHandler<PurchaseOrderPayFragment, PurchaseOrderPayPage> {
	private static final String PREFERENCES_NAME = "com.viphuli.app";
	private static final String PREFERENCES_WECHAT_ORDER_ID_KEY = "pay_wechat_order_id_key";
	private static final String PREFERENCES_WECHAT_PAY_TYPE_KEY = "pay_wechat_pay_type_key";

	@Override
	public void deal() {
		
		PurchasePayInfo payInfo = page.getPayInfo();
		
		String orderId = caller.getOrderId();
		int payType = caller.getPayType();
		
		storeOrderId(orderId);
		storePayType(payType);

		if (payInfo != null && payInfo.getWeichat() != null) {

			WXPayOrder wxPayOrder = new WXPayOrder();
			wxPayOrder.setAppid(payInfo.getWeichat().getAppId());
			wxPayOrder.setNoncestr(payInfo.getWeichat().getNoncestr());
			wxPayOrder.setPackageStr(payInfo.getWeichat().getPackageStr());
			wxPayOrder.setPartnerid(payInfo.getWeichat().getPartnerId());
			wxPayOrder.setPrepayid(payInfo.getWeichat().getPrepayId());
			wxPayOrder.setTimestamp(payInfo.getWeichat().getTimestamp());
			wxPayOrder.setSign(payInfo.getWeichat().getSign());

			WeicahtPayHelper.getInstance().pay(caller.getActivity(), wxPayOrder);

		} else {
			ViewUtils.toast("订单支付信息为空");
		}
	}

	public static void storeOrderId(String orderId) {
		SharedPreferences pref = MyApp.getInstance().getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
		Editor editor = pref.edit();
		editor.putString(PREFERENCES_WECHAT_ORDER_ID_KEY, orderId);
		editor.commit();
	}
	
	public static String gainOrderId() {
		SharedPreferences pref = MyApp.getInstance().getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
		String orderId = pref.getString(PREFERENCES_WECHAT_ORDER_ID_KEY, null);
		return orderId;
	}
	
	public static void storePayType(int payType) {
		SharedPreferences pref = MyApp.getInstance().getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
		Editor editor = pref.edit();
		editor.putInt(PREFERENCES_WECHAT_PAY_TYPE_KEY, payType);
		editor.commit();
	}
	
	public static int gainPayType() {
		SharedPreferences pref = MyApp.getInstance().getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
		int payType = pref.getInt(PREFERENCES_WECHAT_PAY_TYPE_KEY, 0);
		return payType;
	}

}
